package com.tieland.xunda.common.sys;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.Locale;

import net.buffalo.service.ServiceRepository;
import net.buffalo.service.BuffaloWorker;
import net.buffalo.web.upload.UploadWorker;
import net.buffalo.web.RequestUtils;
import net.buffalo.request.RequestWorker;
import net.buffalo.request.RequestContextUtil;
import net.buffalo.request.ValidationException;
import net.buffalo.request.RequestContext;
import net.buffalo.view.ViewWorker;

/**
 * User: qiukx
 * Date: 2008-7-29
 * Company: Freshpower
 * Description:
 */
public class PicoBuffaloAdapter extends HttpServlet {
    private static final long serialVersionUID = 7545714733073313390L;

	private static final Logger logger = Logger.getLogger(PicoBuffaloAdapter.class);

	private static final String LOCALE_COOKIE_NAME = "net.buffalo.web.locale";

	public String getServletInfo() {
		return "Buffalo Application Gateway Servlet";
	}

	/**
	 * Initialize the service, including the service object.
	 */
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		initServiceRepository();
	}

	/**
	 * initialize the service repository
	 *
	 */
	protected void initServiceRepository() {

		if (getServletContext().getAttribute(ServiceRepository.WEB_CONTEXT_KEY) == null) {
			logger.info("initialize the service repository");
			ServiceRepository repository = new PicoServiceRepository(getServletContext());
			getServletContext().setAttribute(ServiceRepository.WEB_CONTEXT_KEY, repository);
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doRequest(request, response);
	}

	protected void doRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		RequestContextUtil.createRequestContext(getServletContext(), request, response);
		String pathInfo = request.getPathInfo();

		logger.debug("request path info: " + pathInfo);
		RequestWorker worker = null;
		if (pathInfo == null || pathInfo.equals("/")) {
			worker = new ViewWorker();
		} else if (pathInfo.startsWith("/view/")) {
			worker = new ViewWorker();
		} else if (pathInfo.startsWith("/buffalo/")) {
			worker = new BuffaloWorker();
		} else if (pathInfo.startsWith("/upload/")) {
			worker = new UploadWorker();
		} else {
			throw new ServletException("Cannot find the request worker!");
		}

		try {
			worker.validate(request, response);
		} catch (ValidationException ex) {
			throw new ServletException("Service validation error", ex);
		}

		worker.processRequest(request, response);
	}

	protected Locale getLocaleFromRequest()
			throws ServletException {
		Cookie cookie = (Cookie) RequestContext.getContext().getCookie().get(LOCALE_COOKIE_NAME);

		if (cookie != null)
			return RequestUtils.getLocale(cookie.getValue());

		return RequestContext.getContext().getHttpRequest().getLocale();
	}
}
